package cn.sinata.wanglin.mine.fragment;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.JsonObject;
import com.xilada.xldutils.activitys.CropImageActivity;
import com.xilada.xldutils.activitys.SelectPhotoDialog;
import com.xilada.xldutils.fragment.BaseLazyFragment;
import com.xilada.xldutils.utils.ActivityUtil;
import com.xilada.xldutils.utils.FileUtils;
import com.xilada.xldutils.utils.SharedPreferencesUtils;
import com.xilada.xldutils.utils.Utils;
import com.xilada.xldutils.xldUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sinata.wanglin.R;
import cn.sinata.wanglin.aliyunoss.OssBean;
import cn.sinata.wanglin.aliyunoss.UpLoadImageUtils;
import cn.sinata.wanglin.commonutils.Constant;
import cn.sinata.wanglin.commonutils.FragmentAdapter;
import cn.sinata.wanglin.mine.activity.AppsettingActivity;
import cn.sinata.wanglin.mine.activity.MessageCenterActivity;
import cn.sinata.wanglin.mine.myinterface.MineDataInterface;
import cn.sinata.wanglin.model.Userinfo;
import cn.sinata.wanglin.net.HttpManager;
import cn.sinata.wanglin.net.model.ResultData;
import cn.sinata.wanglin.net.model.util.ResultDataSubscriber;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

/**
 * description：
 * Created by kaihongwu on 2016/12/05 下午 12:00
 */
public class MineFragment extends BaseLazyFragment {
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.tv_mine_wanglinid)
    TextView tv_mine_wanglinid;//开心网邻ID
    @BindView(R.id.tv_mine_username)
    TextView tv_mine_username;//昵称
    @BindView(R.id.headview_mine)
    SimpleDraweeView headview_mine;//头像
    @BindView(R.id.iv_mine_baguatucao)
    TextView iv_mine_baguatucao;//八卦吐槽
    @BindView(R.id.iv_cardetail_servicenum)
    TextView iv_cardetail_servicenum;//邻里好友
    @BindView(R.id.iv_cardetail_goodping)
    TextView iv_cardetail_goodping;//扬言被赞
    @BindView(R.id.viewpager)
    ViewPager viewpager;//
    @BindView(R.id.tabs)
    TabLayout tabs;//
    @BindView(R.id.toolbar)
    Toolbar toolbar;//
    @BindView(R.id.collapsing_toolbar)
    CollapsingToolbarLayout mCollapsingToolbarLayout;
    PersonInfoFragment mPersonInfoFragment;
    QuanzibaguaFragment mQuanzibaguaFragment;
    XiaoquLifeFragment mXiaoquLifeFragment;

    @Override
    protected int getContentViewLayoutID() {

        return R.layout.fragment_mine;
    }

    @Override
    protected void onFirstVisibleToUser() {
        setHasOptionsMenu(true);
        setupViewPager();
        showDialog();
        getUserinfo();

    }

    private void setBasicinfo() {
        String sex = SharedPreferencesUtils.getString(Constant.SP_SEX);
        String wanglinid = SharedPreferencesUtils.getString(Constant.SP_WANGLINID);
        String nickname = SharedPreferencesUtils.getString(Constant.SP_NICKNAME);
        String headurl = SharedPreferencesUtils.getString(Constant.SP_HEADURL);
        if (!TextUtils.isEmpty(headurl)) {
            headview_mine.setImageURI(headurl);
        }
        if (!TextUtils.isEmpty(wanglinid)) {
            tv_mine_wanglinid.setText("ID:" + wanglinid);
        }
        if (!TextUtils.isEmpty(nickname)) {
            tv_mine_username.setText(nickname);
        }
        if (TextUtils.isEmpty(sex) || "1".equals(sex)) {
            Resources res = getResources();
            Drawable img_off = res.getDrawable(R.mipmap.gril);
            // 调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
            img_off.setBounds(0, 0, img_off.getMinimumWidth(), img_off.getMinimumHeight());
            tv_mine_username.setCompoundDrawables(null, null, img_off, null); //设置右图标
        } else {
            Resources res = getResources();
            Drawable img_off = res.getDrawable(R.mipmap.boy);
            // 调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
            img_off.setBounds(0, 0, img_off.getMinimumWidth(), img_off.getMinimumHeight());
            tv_mine_username.setCompoundDrawables(null, null, img_off, null); //设置右图标
        }
    }

    @Override
    protected void onVisibleToUser() {

    }

    @Override
    protected void onInvisibleToUser() {

    }

    private void setupViewPager() {

        ((AppCompatActivity) context).setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActivityUtil.create(MineFragment.this).go(MessageCenterActivity.class)
                        .start();
            }
        });
        mCollapsingToolbarLayout.setTitle(" ");
        List<String> titles = new ArrayList<>();
        titles.add("个人信息");
        titles.add("圈子八卦");
        titles.add("小区生活");
        List<Fragment> mFragments = new ArrayList<>();
        mPersonInfoFragment = new PersonInfoFragment();
        String userid = SharedPreferencesUtils.getString(Constant.SP_USERID);
        mQuanzibaguaFragment = QuanzibaguaFragment.newInstance(userid);
        mXiaoquLifeFragment = new XiaoquLifeFragment();
        mFragments.add(mPersonInfoFragment);
        mFragments.add(mQuanzibaguaFragment);
        mFragments.add(mXiaoquLifeFragment);
        FragmentAdapter adapter = new FragmentAdapter(getChildFragmentManager(), mFragments, titles);
        viewpager.setOffscreenPageLimit(3);
        viewpager.setAdapter(adapter);
        tabs.setupWithViewPager(viewpager);
        mPersonInfoFragment.addMineDataInterface(new MineDataInterface() {
            @Override
            public void onRefresh(int type) {
                //0:刷新全部数据，1：刷新头像，2：刷新昵称，3：刷新性别
                switch (type) {
                    case 0:
                        //暂时在外面刷新
                        showDialog();
                        getUserinfo();
                        break;
                    case 1:
                        String headurl = SharedPreferencesUtils.getString(Constant.SP_HEADURL);
                        headview_mine.setImageURI(headurl);
                        break;
                    case 2:
                        String nickname = SharedPreferencesUtils.getString(Constant.SP_NICKNAME);
                        if (!TextUtils.isEmpty(nickname)) {
                            tv_mine_username.setText(nickname);
                        } else {
                            tv_mine_username.setText("开心网邻用户");
                        }
                        break;
                    case 3:
                        String sex = SharedPreferencesUtils.getString(Constant.SP_SEX);
                        if (TextUtils.isEmpty(sex) || "1".equals(sex)) {
                            Resources res = getResources();
                            Drawable img_off = res.getDrawable(R.mipmap.gril);
                            // 调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
                            img_off.setBounds(0, 0, img_off.getMinimumWidth(), img_off.getMinimumHeight());
                            tv_mine_username.setCompoundDrawables(null, null, img_off, null); //设置右图标
                        } else {
                            Resources res = getResources();
                            Drawable img_off = res.getDrawable(R.mipmap.boy);
                            // 调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
                            img_off.setBounds(0, 0, img_off.getMinimumWidth(), img_off.getMinimumHeight());
                            tv_mine_username.setCompoundDrawables(null, null, img_off, null); //设置右图标
                        }
                        break;
                }
            }
        });

    }

    /**
     * 获取个人信息页面
     */
    public void getUserinfo() {
        String userid = SharedPreferencesUtils.getString(Constant.SP_USERID);
        Observable<ResultData<Userinfo>> observable = HttpManager.getUserinfo("" + userid, "" + userid);
        observable.subscribeOn(Schedulers.io())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        showDialog();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultDataSubscriber<Userinfo>(this) {
                    @Override
                    public void onSuccess(String msg, Userinfo userinfo) {
//                        showToast(msg);
                        SharedPreferencesUtils.save(Constant.SP_HEADURL, userinfo.getHeadUrl());
                        SharedPreferencesUtils.save(Constant.SP_NICKNAME, userinfo.getNickName());
                        setDataForUser(userinfo);
                        if (mPersonInfoFragment != null && !mPersonInfoFragment.isDetached()) {
                            mPersonInfoFragment.setRefreshFinish();
                            mPersonInfoFragment.setDataForUser(userinfo);
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        if (mPersonInfoFragment != null && !mPersonInfoFragment.isDetached()) {
                            mPersonInfoFragment.setRefreshFinish();
                        }
                    }
                });
    }

    private void setDataForUser(Userinfo userinfo) {

        if (!TextUtils.isEmpty(userinfo.getCounts())) {
            iv_mine_baguatucao.setText("八卦吐槽\n" + userinfo.getCounts());
        } else {
            iv_mine_baguatucao.setText("八卦吐槽\n0");
        }
        if (!TextUtils.isEmpty(userinfo.getFriends())) {
            iv_cardetail_servicenum.setText("邻里好友\n" + userinfo.getFriends());
        } else {
            iv_cardetail_servicenum.setText("邻里好友\n0");
        }
        if (!TextUtils.isEmpty(userinfo.getLikes())) {
            iv_cardetail_goodping.setText("扬言被赞\n" + userinfo.getLikes());
        } else {
            iv_cardetail_goodping.setText("扬言被赞\n0");
        }
        headview_mine.setImageURI(userinfo.getHeadUrl());

        if (!TextUtils.isEmpty(userinfo.getAccount())) {
            tv_mine_wanglinid.setText("ID:" + userinfo.getAccount());
        }
        if (!TextUtils.isEmpty(userinfo.getNickName())) {
            tv_mine_username.setText(userinfo.getNickName());
        } else {
            tv_mine_username.setText("开心网邻用户");
        }
        if (TextUtils.isEmpty(userinfo.getSex()) || "1".equals(userinfo.getSex())) {
            Drawable img_off = ContextCompat.getDrawable(context,R.mipmap.gril);
//            // 调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
//            img_off.setBounds(0, 0, img_off.getMinimumWidth(), img_off.getMinimumHeight());
            tv_mine_username.setCompoundDrawablesWithIntrinsicBounds(null, null, img_off, null); //设置右图标
        } else {
            Drawable img_off = ContextCompat.getDrawable(context,R.mipmap.boy);
//            // 调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
//            img_off.setBounds(0, 0, img_off.getMinimumWidth(), img_off.getMinimumHeight());
            tv_mine_username.setCompoundDrawablesWithIntrinsicBounds(null, null, img_off, null); //设置右图标
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.toolmenu, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_setting:
                ActivityUtil.create(this).go(AppsettingActivity.class)
                        .start();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    public void addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener listener) {
        if (appbar != null) {
            appbar.addOnOffsetChangedListener(listener);
        }
    }

    public void removeOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener listener) {
        if (appbar != null) {
            appbar.removeOnOffsetChangedListener(listener);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case 5:
                    if (data!=null){
                        String path = data.getStringExtra(SelectPhotoDialog.DATA);
                        cropImage(path);
                    }
                    break;
                case 6:
                    if (data!=null){
                        String path = data.getStringExtra("path");
                        updateHead(path);
                    }
                    break;
            }
        }

    }

    private void cropImage(String path){
        ActivityUtil.create(this).go(CropImageActivity.class)
                .put("uri",path)
                .put("mode",1)
                .startForResult(6);
    }

    private void updateHead(final String path){
        Utils.systemErr("-path-->"+path);
        final ArrayList<OssBean>  mOssBeans=new ArrayList<>();
        mOssBeans.add(new OssBean(path));
        Observable<List<OssBean>> mObservable= new UpLoadImageUtils(mOssBeans).uploadimg();
        mObservable.doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showDialog("上传中...");
            }
        })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<OssBean>>() {
                    @Override
                    public void onCompleted() {
                        dismissDialog();
                    }
                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(List<OssBean> ossBeen) {
                        if(ossBeen!=null&&ossBeen.size()!=0){
                            alterUserinfo(ossBeen.get(0).getUrlkey());
                        }
                    }
                });


    }

    private  void alterUserinfo(final String datamsg){
        String userid= SharedPreferencesUtils.getString(Constant.SP_USERID);
        Observable<ResultData<JsonObject>> observable = HttpManager.updUser(""+userid,datamsg,Constant.ALT_headUrl);
        observable.subscribeOn(Schedulers.io())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        showDialog();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultDataSubscriber<JsonObject>(this) {
                    @Override
                    public void onSuccess(String msg, JsonObject jsonObject) {
                        showToast(msg);
                        SharedPreferencesUtils.save(Constant.SP_HEADURL, datamsg);
                        String headurl = SharedPreferencesUtils.getString(Constant.SP_HEADURL);
                        headview_mine.setImageURI(headurl);
                        if (!TextUtils.isEmpty(xldUtils.PICDIR)) {
                            FileUtils.deleteFiles(new File(xldUtils.PICDIR));
                        }
                    }
                });

    }

    @OnClick(R.id.headview_mine)
    void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.headview_mine:
                ActivityUtil.create(this).go(SelectPhotoDialog.class).startForResult(5);
                break;
        }
    }
}
